<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function Node(val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }
        var a = new Node(1)
        var b = new Node(null)
        var c = new Node(2)
        var d = new Node(3)
        var e = new Node(4)
        var f = new Node(5)
        var g = new Node(5)
        a.left = b
        a.right = c
        b.left = d
        b.right = e
        c.left = f
        c.right = g

        var pathSum = (root, targetSum) => {
            if (!root) {
                return []
            }
            // ans作为结果数组
            let ans = []
            return traverse(root, targetSum - root.val, [root.val], ans)
        } 

        function traverse (cur, count, temp, ans) {
            if (!cur.left && !cur.right && count === 0) {
                // 注意temp值要用扩展运算法展开传递进去，否则后面回溯会影响他
                ans.push([...temp])
                return ans // 叶子节点找到路径
            }
            if (!cur.left && !cur.right) return ans // 叶子结点没有找到路径

            if(cur.left) {
                count -= cur.left.val
                temp.push(cur.left.val)
                traverse(cur.left, count, temp, ans)
                // 回溯
                count += cur.left.val
                temp.pop()
            }

            if (cur.right) {
                count -= cur.right.val
                temp.push(cur.right.val)
                traverse(cur.right, count, temp, ans)
                // 回溯
                count += cur.right.val
                temp.pop()
            }
            return ans
        }

        console.log(pathSum(a, 8));
        // console.log(aa);
        // console.log(pathSum(aa, 5));
    </script>
</body>

</html>